// pages/submit_order/submit_order.js
var api = require('../../api/api');

var now_time = new Date();
var year = now_time.getFullYear();
var month = now_time.getMonth() + 1;
if (month < 10) {
  var month = "0" + month;
}
var date = now_time.getDate();
if (date < 10) {
  var date = "0" + date;
}
var hour = now_time.getHours();
if (hour < 10) {
  var hour = "0" + hour;
}
var minute = now_time.getMinutes();
if (minute < 10) {
  var minute = "0" + minute;
}
var second = now_time.getSeconds();
if (second < 10) {
  var second = "0" + second;
}
var now_date = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shop_id:'',
    selectDate: 0,
    machineShow: false,
    longitude: '',
    latitude: '',
    my_address: {},
    shop_count: 0,
    worker_count: 0,
    shop_lists: [],
    markers: [],
    selectedService: {}, //选择的服务
    serviceTxt: '请选择服务',
    cur_position: "广州市番禺大涌路",
    workerId: 0,
    workerTxt: '可不选',
    car_options: [{
      name: "黑色",
    }],
    selectCar: {},
    selectCoupon: {
      id: 0,
      price: 0
    },
    service: {
      id:''
    },
    pay_way: 1,
    payWayArr: ['余额支付', '微信支付', '次数卡'],
    remark: '',
    showUserCard: false,
    selectUserCard: {
      id: 0,
      title: '请选择'
    },
    remarkAddress:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.picker = this.selectComponent("#picker");
    this.setData({
      service: wx.getStorageSync('selectService')
    })

    if (options) {
      console.log('xx',options)
      let selectedService = this.data.selectedService;
      selectedService.id = options.sid;
      selectedService.price = 0;
      selectedService.tit = options.tit;
      this.setData({
        'service.id':options.sid,
        shop_id:options.shop_id,
        serviceTxt: options.tit,
        selectedService: selectedService
      })
    }
    this.select_car();
  },
  bindPickerChange(e) {
    console.log(e.detail.value);
    if (e.detail.value == 2) {
      this.setData({
        selectCoupon: {
          id: 0,
          price: 0
        },
        showUserCard: true
      })
    } else {
      this.setData({
        selectUserCard: {
          id: 0,
          title: '请选择'
        },
        showUserCard: false,
        'selectUserCard.servicePrice':this.data.selectedService.price - this.data.selectCoupon.price
      })
    }
    this.setData({
      pay_way: e.detail.value
    })


  },
  timeOpen() {
    this.picker.showDialog();
  },
  cleartime() {
    this.setData({
      selectDate: ''
    })
  },
  confirm(e) {
    this.setData({
      selectDate: e.detail.selectDate
    })
  },
  editAddress(e) {
    this.setData({
      'my_address.address': e.detail.value
    })
  },
  
  //点击返回
  click_back() {
    wx.navigateBack({
      delta: 1,
    })
  },
  //我的服务
  click_my_service() {
    wx.navigateTo({
      url: '../select_service/select_service?page=submit&shop_id='+this.data.shop_id,
    })

  },
  //选择车辆
  click_select_car(e) {
    let serviceId = e.currentTarget.dataset.service_id;
    if (!serviceId) {
      wx.showToast({
        title: '请先选择服务',
        icon: 'none'
      })
      return false;
    }
    wx.navigateTo({
      url: '../car_list/car_list?service_id=' + serviceId,
    })
  },
  formSubmit(e) {
    if (!this.data.selectedService.id) {
      wx.showToast({
        title: '请选择服务',
        icon: 'none'
      })
      return false;
    }

    if (!this.data.selectCar) {
      wx.showToast({
        title: '请选择车辆',
        icon: 'none'
      })
      return false;
    }

    if (this.data.pay_way == 2 && !this.data.selectUserCard.id) {
      wx.showToast({
        title: '请选择支付卡券',
        icon: 'none'
      })
      return false;
    }
    let address = '';
    if(this.data.remarkAddress){
      address = this.data.my_address.address+' ('+this.data.remarkAddress+') '
    }else{
      address =this.data.my_address.address;
    }
    api.post('/appoint/payService', {
      pay_way: this.data.pay_way,
      service_id: this.data.selectedService.id,
      worker_id: this.data.workerId,
      appoint_time: this.data.selectDate,
      car_id: this.data.selectCar.id,
      user_coupon_id: this.data.selectCoupon.id,
      user_card_id: this.data.selectUserCard.id,
      longitude: this.data.longitude,
      latitude: this.data.latitude,
      address: address,
      remark: this.data.remark
    }).then(res => {
        if(!res.payInfo){
          wx.showToast({
            title: res.message,
            icon: 'none',
            success() {
              setTimeout(() => {
                wx.reLaunch({
                  url: '/pages/car_order/order_detail/order_detail?order_id=' + res.order_id,
                })
              }, 1000)
            }
          })
        }else{
          wx.requestPayment({
            ...res.payInfo,
            success: function (payRes) {
              console.log('success:' + JSON.stringify(payRes));
              wx.showToast({
                title: '下单成功',
                icon: 'none',
                success: function () {
                  setTimeout(() => {
                    wx.reLaunch({
                      url: '/pages/car_order/order_detail/order_detail?order_id=' + res.order_id,
                    })
                  }, 1000)
                }
              })
            },
            fail: function (err) {
              console.log('fail:' + JSON.stringify(err));
              if (err.errMsg == "requestPayment:fail cancel") {
                wx.showToast({
                  title: '取消支付',
                  icon: 'none',
                  duration: 3000
                })
              } else {
                wx.showToast({
                  title: JSON.stringify(err),
                  icon: 'none',
                  duration: 3000
                })
              }
            }
          });
        }
    })
  },
  click_select_technician() {
    wx.navigateTo({
      url: '../technicians/technicians?shop_id='+this.data.shop_id
    })
  },
  //选择优惠券
  click_select_coupon() {
    if (!this.data.selectedService && !this.data.selectedService.id) {
      wx.showToast({
        title: '请选择服务',
        icon: "none"
      })
      return false;
    }


    wx.navigateTo({
      url: '../my_coupons/my_coupons?isUse=1&price='+this.data.selectedService.price+'&latitude=' + this.data.latitude + '&longitude=' + this.data.longitude + '&service_id=' + this.data.selectedService.id+'&shop_id=' + this.data.shop_id,
    })
  },
  //选择卡券
  click_select_card() {
    if (!this.data.selectedService && !this.data.selectedService.id) {
      wx.showToast({
        title: '请选择服务',
        icon: "none"
      })
      return false;
    }

    if (!this.data.selectCar && !this.data.selectCar.id) {
      wx.showToast({
        title: '请选择车辆',
        icon: "none"
      })
      return false;
    }
    wx.navigateTo({
      url: '/pages/member_card/my_card/my_card?isUse=1&latitude=' + this.data.latitude + '&longitude=' + this.data.longitude + '&service_id=' + this.data.selectedService.id + "&car_id=" + this.data.selectCar.id+"&price="+this.data.selectedService.price+"&car_num="+this.data.selectCar.plate_numbe+"&shop_id="+this.data.shop_id,
      fail: function (res) {
        console.log(res)
      }
    })

  },
  //点击当前位置
  click_cur_position() {
    let that = this;
    wx.chooseLocation({
      success: res => {
        console.log('选择地址', res)
        wx.setStorageSync('Location', res);
        let my_address = that.data.my_address;
        my_address.address = res.address;
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
          my_address: my_address
        })
        that.getShop(res.longitude, res.latitude)
    
        
      },fail(err){
        console.log('地址',err)
      }
    })
  },
  //获取定位
  checkSetting() {
    let that = this;
    wx.getSetting({
      success(res) {
        console.log("getSetting", res);
        if (!res.authSetting['scope.userLocation']) {
          // 接口调用询问  
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              that.getLocation();
            },
            fail() {
              // 用户拒绝了授权  
              wx.showModal({
                title: '提示',
                content: '拒绝后无法为你推荐实时定位信息，请授权定位信息',
                success(res) {
                  if (res.confirm) {
                    // 打开设置页面  
                    wx.openSetting({
                      success: function (data) {
                        console.log("openSetting: success");
                      },
                      fail: function (data) {
                        console.log("openSetting: fail", data);
                      }
                    });
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
            }
          })
        } else {
          console.log("1-已经授权权限");
          that.getLocation()
        }
      },
      fail(res) {
        console.log("getSetting: success");
        console.log(res);
      }
    })

  },
  getLocation() {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        wx.setStorageSync("Location", res)
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
        })
        that.getShop(res.longitude, res.latitude);
      },
      fail(res) {
        console.log('失败', res)
      }
    })
  },
  getShop(longitude, latitude) {
    let that = this;
    api.get('/common/getShops', {
      longitude: longitude,
      latitude: latitude,
      limit: 1000
    }).then(shopRes => {
      console.log("附近商店", shopRes)
      let markers = [];
      let shopLists = shopRes.shops;
      shopLists.forEach(element => {
        markers.push({
          iconPath: "/images/icon.png",
          longitude: element.longitude,
          latitude: element.latitude,
          id: element.id,
          width: 16,
          height: 16
        })
      });
      let address = ""
     
      if(that.data.my_address.address){
        address = that.data.my_address;
      }else{
        address = shopRes.address;
      }
      
      that.setData({
        markers: markers,
        shop_count: shopRes.shop_count,
        worker_count: shopRes.worker_count,
        my_address:address,
        shop_lists: shopRes.shops
      })
    })
  },
  select_car() {

    let that = this;

    let location = wx.getStorageSync('Location')
    api.post('/appoint/servicePrice', {
      service_id: this.data.service.id,
      car_id: 0
    }).then(res => {
      this.setData({
        selectCar: res.car,
        'selectedService.price': res.price,
        'selectedService.member_price': res.member_price
      })

    })
    return false;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (!this.data.latitude && !this.data.longitude) {
      this.checkSetting();
    }
    if (this.data.selectedService) {
      this.setData({
        serviceTxt: this.data.selectedService.tit
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})